﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twitter;
using System.ComponentModel.Design;
using FriendsNearby.Services;
using FriendsNearby.Services.Facebook;
using FriendsNearby.Services.Entities;
using System.Globalization;
using InSTEDD.Labs.Geo;
using InSTEDD.Labs.Geo.Locators;

namespace FriendsNearbyBot
{
    internal class PingProcessor : IMessageProcessor
    {
        IUsersService userService;
        ILocationService locationService;
        IMessageBuilder messageBuilder;

        public PingProcessor(IUsersService userService, ILocationService locationService) : 
            this(userService, locationService, new PlainTextMessageBuilder())
        {
        }

        public PingProcessor(IUsersService userService, ILocationService locationService, IMessageBuilder messageBuilder)
        {
            this.userService = userService;
            this.locationService = locationService;
            this.messageBuilder = messageBuilder;
        }

        public bool CanProcess(Message message)
        {
            return message.Text == "ping";
        }

        public RunNextProcessor Process(IBotClient client, Message message)
        {
            if (CanProcess(message))
            {
                messageBuilder.Clear();
				UserRegistry user = userService.QueryUserRegistry(x => x.TwitterScreenName == message.Sender.ScreenName);

                LocationInfo lastUpdate = locationService.GetLastLocationInfo(user.UserID);

                string actualDateStr = TextHelper.FormatDateTimeAsUtc(DateTime.Now);
                if (lastUpdate != null)
                {
                    CountryLocator countries = CountryLocator.FromFile(@"country_borders\Country_Borders.txt");
                    Country country = countries.GetCountryForPoint(lastUpdate.Location);
                    string lastLocationStr;

                    if (country != null)
                        lastLocationStr = country.Name;
                    else
                        lastLocationStr = lastUpdate.Location.ToString();

                    string dateLastLocationStr = TextHelper.FormatDateTimeRelativeToNow(lastUpdate.When);
                    messageBuilder.AppendFragment(String.Format(Properties.Resources.PingMessage, lastLocationStr, dateLastLocationStr, actualDateStr));
                }
                else
                {
                    messageBuilder.AppendFragment(String.Format(Properties.Resources.PingMessageError, actualDateStr));
                }

                client.SendMessages(message.Sender.ScreenName, messageBuilder.GetMessages(), message, this.GetType().Name);

                BotProcessor.MessageProcessed(client, message);

                return RunNextProcessor.No;
            }
            else
                return RunNextProcessor.Yes;
        }
    }
}

